/*
 * @lc app=leetcode id=142 lang=cpp
 *
 * [142] Linked List Cycle II
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if (!head) {
            return NULL;
        }

        ListNode * fast = findCycle(head);
        if (!fast) {
            return NULL;
        }

        ListNode *p = fast->next;
        ListNode *q = head;

        int lp = getLen(p, fast);
        int lq = getLen(q, fast);
        int l = lp-lq;

        if (l < 0) {
            l = -l;
            p = head;
            q = fast->next;
        }

        while (l-- > 0) {
            p = p->next;
        }

        while (p != q) {
            p = p->next;
            q = q->next;
        }
        return p;
    }

    ListNode* findCycle(ListNode *head) {
        ListNode *fast = head->next;
        ListNode *slow = head;

        while(fast && slow) {
            if (fast == slow) {
                return fast;
            }

            if (fast->next) {
                fast = fast->next->next;
            } else {
                return NULL;
            }

            slow = slow->next;
        }
        return NULL;
    }

    int getLen(ListNode *node, ListNode *tail) {
        int l = 0;
        while(node != tail) {
            node = node->next;
            l++;
        }
        return l;
    }
};


